package com.ztools.pc.listener;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.rabbitmq.client.Channel;
import com.ztools.api.service.pc.PcPayService;
import com.ztools.common.config.rabbitMq.config.QueueConfig;
import com.ztools.common.model.wx.payment.Cart;
import com.ztools.common.util.common.Result;
import com.ztools.common.util.common.ResultCode;
import com.ztools.pc.service.card.CardMasterService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * @Author: seeTools
 * @Date: 2023/6/9  10:18
 * @Version 1.0
 */
@Component
public class RabbitMqListener {

    private final Logger log = LoggerFactory.getLogger(getClass());

    @Resource
    private PcPayService pcPayService;
    @Resource
    private CardMasterService cardMasterService;

    /**
     * 订单监听
     *
     * @param message message
     * @param channel channel
     */
    @RabbitListener(queues = QueueConfig.ORDER_QUEUE)
    public void listenerOrderQueue(Message message, Channel channel) {
        String orderStr = new String(message.getBody());
        log.info("订单数据:{}", orderStr);
        Cart cart = JSONUtil.toBean(orderStr, Cart.class);
        try {
            Result result = pcPayService.save(cart);
            if (ResultCode.ERROR.getCode() == result.getCode()) {
                // 拒绝接受消息，放入到死信队列中
                channel.basicNack(message.getMessageProperties().getDeliveryTag(), true, false);
            }
        } catch (Exception e) {
            try {
                // 如果有异常，也放到死信队列中
                channel.basicNack(message.getMessageProperties().getDeliveryTag(), true, false);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }

    /**
     * 开卡监听
     *
     * @param message message
     * @param channel channel
     */
    @RabbitListener(queues = QueueConfig.OPEN_CARD_QUEUE)
    public void listenerOpenCardQueue(Message message, Channel channel) {
        String memberId = new String(message.getBody());
        if (StrUtil.isNotEmpty(memberId)) {
            log.info("开卡会员ID为:{}", memberId);
            boolean b = cardMasterService.openCard(Long.parseLong(memberId));
            try {
                if (!b) {
                    channel.basicNack(message.getMessageProperties().getDeliveryTag(), true, false);
                }
            } catch (IOException e) {
                try {
                    channel.basicNack(message.getMessageProperties().getDeliveryTag(), true, false);
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }
    }

}
